package com.loves.admin.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class MailUtil {

    private Logger logger = LoggerFactory.getLogger(MailUtil.class);

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public boolean sendMail(String toName,String subject,String text) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        try {
            helper.setFrom(from);
            helper.setTo(toName);
            helper.setSubject(subject);
            helper.setText(text);
            mailSender.send(mimeMessage);
            logger.info("邮件发送成功");
            return true;
        } catch (Exception e) {
            logger.error("邮件发送失败, to: {}", toName, e);
            return false;
        }
    }
}
